//
//  DetailViewController.m
//  DemoMeshtiles
//
//  Created by MAC on 7/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController
@synthesize photoId;
@synthesize photoData=_photoData;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.barStyle=UIBarStyleBlack;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)viewWillAppear:(BOOL)animated {
    
   
    [self.tableView setBackgroundColor:[UIColor colorWithRed:237*1.0f/255 green:234*1.0f/255 blue:229*1.0f/255 alpha:1]];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    NSMutableString *link=[[NSMutableString alloc] initWithString:@"http://ec2-107-20-246-0.compute-1.amazonaws.com/api/View/getListPhotoDetail?list_photo_id="];
    [link appendString:photoId] ;
    [link appendFormat:@"&user_id=1d6311db-6a2e-4362-a3c3-2a7a7814f7a4"];
    NSLog(@"Gen link: %@",link);
    
    //
    NSURL *url = [NSURL URLWithString:link];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setDelegate:self];
    [request startAsynchronous];
    
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    
    NSData *responseData = [request responseData];
    SBJsonParser *parser=[[SBJsonParser alloc] init];
    NSString *jsonString=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSDictionary *status=(NSDictionary *)[parser objectWithString:jsonString error:nil];
    if ([status objectForKey:@"is_success"]!=0) {//Load photo to array if success
        _photoData=[[status objectForKey:@"photo"] objectAtIndex:0];

        
    } 
    [self.tableView reloadData];
    
    
}
#pragma mark -
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.

    NSArray *commentArray=[_photoData objectForKey:@"comment"];
    return ([commentArray count]+1);
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"PhotoCell";
    static NSString *CommentTableIdentifier=@"CommentCell";
    if ([indexPath row]==0) {//photo cell
        CustomListCellCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
        //NSDictionary *dict=(NSDictionary*)[_photoData objectAtIndex:[indexPath section]];
        if (cell == nil) {
            NSLog(@"Row =%d", [indexPath row]);
            cell=[[CustomListCellCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier withData:_photoData];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }  
        [cell setCellData:_photoData];
        return cell; 
    } else {
        
        NSArray *commentArray=[_photoData objectForKey:@"comment"];
        CommentCell *cell=[tableView dequeueReusableCellWithIdentifier:CommentTableIdentifier];
        if (cell == nil) {
            
            NSLog(@"Row =%d", [indexPath row]);
            cell=[[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CommentTableIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }   
        [cell setCellData:[commentArray objectAtIndex:([indexPath row]-1)]];
        
        return cell;
    }
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int row=[indexPath row];
    if (row==0) {
        return 432;
    } else {
        CGRect commentRect = CGRectMake(70, 30, 310-70, 15);
        UILabel *comment = [[UILabel alloc] initWithFrame:commentRect]; 
        comment.textColor=[UIColor grayColor];
        comment.font=[UIFont systemFontOfSize:12];
        //Update comment
        
        NSArray *commentArr=[_photoData objectForKey:@"comment"];
        NSDictionary *commentObj=[commentArr objectAtIndex:([indexPath row]-1)];
        NSString *beforeDecodeStr=[commentObj objectForKey:@"content"];       
        NSString *commentStr=[beforeDecodeStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        CGSize maximumLabelSize = CGSizeMake(296,9999);
        CGSize expectedLabelSize = [commentStr sizeWithFont:comment.font 
                                          constrainedToSize:maximumLabelSize 
                                              lineBreakMode:comment.lineBreakMode]; 
        
        //adjust the label the the new height.
        CGRect newFrame = comment.frame;
        newFrame.size.height = expectedLabelSize.height;
        comment.frame = newFrame;
        comment.text=commentStr;
        //
        int cellHeight=30+(newFrame.size.height)+10;//bonus 10
        if (cellHeight<70) cellHeight=70;
        [comment release];
        return cellHeight;
    }
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

@end
